<template>
  <view class="map-form">
    <view class="form-header">
      <view class="header-title">{{ isEdit ? "编辑地址" : "查看地址" }}</view>
      <view v-if="!isEdit" class="edit-btn" @tap="toggleEdit">编辑</view>
    </view>

    <!-- 显示地图 -->
    <view class="map-wrapper">
      <map class="map-container" :latitude="mapLocation.latitude" :longitude="mapLocation.longitude" :markers="markers"
        :scale="14" @tap="handleMapTap"></map>
    </view>

    <!-- 位置信息 -->
    <view class="form-item">
      <view class="label">地址信息</view>
      <textarea class="textarea" placeholder="地址信息" v-model="shop.address2" :disabled="!isEdit" />
    </view>

    <!-- 经纬度信息 -->
    <view class="form-item">
      <view class="label">位置信息</view>
      <view class="location-info">
        <view class="location-item">
          <text class="location-label">经度：</text>
          <input class="location-input" type="text" v-model="shop.longitude" :disabled="!isEdit" />
        </view>
        <view class="location-item">
          <text class="location-label">纬度：</text>
          <input class="location-input" type="text" v-model="shop.latitude" :disabled="!isEdit" />
        </view>
      </view>
    </view>

    <!-- 保存按钮 -->
    <view v-if="isEdit" class="btn-wrapper">
      <nut-button class="save-btn" type="primary" @tap="saveAddress">保存</nut-button>
      <nut-button class="cancel-btn" @tap="toggleEdit">取消</nut-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import Taro from "@tarojs/taro";
import http from "@/utils/http";
import { store } from "@/store/index";
import { mapConfig } from "@/utils/config";
const page = Taro.getCurrentInstance().page;
console.log("page $$$", page);
if (page?.config) {
  page.config.enablePullDownRefresh = false
}

// 直接解构store中的响应式状态
const { info, business } = store.storeState;
// 获取页面参数
const router = Taro.getCurrentInstance().router;
const editType = ref(router?.params?.type || "view"); // 默认为查看模式
const isEdit = ref(editType.value === "edit"); // 根据传入的类型判断是否可编辑

const shop = ref<any>({}); // 店铺信息

// 设置导航栏标题
Taro.setNavigationBarTitle({
  title: isEdit.value ? "编辑地址" : "查看地址",
});


// 地图相关状态
const mapLocation = reactive({
  latitude: parseFloat(shop.value.latitude || "22.82402"),
  longitude: parseFloat(shop.value.longitude || "108.320004"),
});
const markers = ref([]);

// 切换编辑模式
function toggleEdit() {
  isEdit.value = !isEdit.value;
  if (!isEdit.value) {
    // 如果取消编辑，重新加载数据
    loadAddressInfo();
  }
}

// 加载地址信息
function loadAddressInfo() {
  // 这里应该调用API获取地址信息
  // 如果有store中的数据，直接使用
  if (business.value && business.value.address) {
    shop.value = {
      id: business.value.id || "",
      address: business.value.address || "",
      latitude: business.value.latitude || "22.82402",
      longitude: business.value.longitude || "108.320004",
    };

    // 更新地图位置
    mapLocation.latitude = parseFloat(shop.value.latitude);
    mapLocation.longitude = parseFloat(shop.value.longitude);
    updateMarker();
  } else {
    // 模拟API调用
    setTimeout(() => {
      shop.value = {
        id: "1",
        address: "广西南宁市青秀区民族大道",
        latitude: "22.82402",
        longitude: "108.320004",
      };

      // 更新地图位置
      mapLocation.latitude = parseFloat(shop.value.latitude);
      mapLocation.longitude = parseFloat(shop.value.longitude);
      updateMarker();
    }, 500);
  }

  // 实际API调用示例
  // http.get(`/api/shop/address`).then((res: any) => {
  //   if (res.code === 0 && res.data) {
  //     shop.value = res.data;
  //     // 更新地图位置
  //     mapLocation.latitude = parseFloat(shop.value.latitude);
  //     mapLocation.longitude = parseFloat(shop.value.longitude);
  //     updateMarker();
  //   }
  // });
}

// 更新地图标记
function updateMarker() {
  markers.value = [
    {
      id: 0,
      latitude: mapLocation.latitude,
      longitude: mapLocation.longitude,
      title: "当前位置",
      width: 30,
      height: 30,
    },
  ];
}

// 处理地图点击事件
async function handleMapTap(e) {
  if (!isEdit.value) return; // 非编辑模式下不响应点击

  mapLocation.latitude = e.detail.latitude;
  mapLocation.longitude = e.detail.longitude;
  updateMarker();

  // 更新表单数据
  shop.value.latitude = e.detail.latitude.toString();
  shop.value.longitude = e.detail.longitude.toString();

  try {
    // 调用腾讯地图API进行逆地址解析
    const res = await Taro.request({
      url: "https://apis.map.qq.com/ws/geocoder/v1/",
      data: {
        location: `${e.detail.latitude},${e.detail.longitude}`,
        key: mapConfig.qqMapKey, // 替换为您的腾讯地图API密钥
        get_poi: 0,
      },
    });

    if (res.data && res.data.status === 0) {
      shop.value.address = res.data.result.address;
    }
  } catch (error) {
    console.error("获取地址信息失败", error);
  }
}

// 保存地址信息
function saveAddress() {
  Taro.showLoading({ title: "保存中..." });
  setTimeout(() => {
    Taro.hideLoading();
  }, 700);

  const param = { ...shop.value };
  delete param.address;
  delete param.balanceA;
  delete param.balanceB;
  delete param.id;
  http.postQuery("/api/merchant/update", param).then((res) => {
    console.log("res", res);
    if (res.code == 0) {
      Taro.showToast({ title: "保存成功", icon: "success" });
      Taro.navigateBack();
    }
    else {
      Taro.showToast({ title: '保存失败', icon: "none" });
    }
  });
}

onMounted(() => {
  // 加载地址信息
  //   loadAddressInfo();
  // 初始化地图标记
  loadNameInfo();
  updateMarker();
});


function loadNameInfo() {

  // 实际API调用示例
  http.post(`/api/merchant/getUserById`).then((res: any) => {
    console.log("res", res);
    if (res.code == 0 && res.data) {
      // nameForm.value = res.data;
      shop.value = res.data[0].columns;
    }
  });
}
</script>

<style lang="scss">
.map-form {
  padding: 30rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
  box-sizing: border-box;

  .form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    .header-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }

    .edit-btn {
      padding: 10rpx 30rpx;
      background-color: #ff6034;
      color: #fff;
      border-radius: 30rpx;
      font-size: 28rpx;
    }
  }

  .map-wrapper {
    margin-bottom: 20rpx;
    border-radius: 12rpx;
    overflow: hidden;

    .map-container {
      width: 100%;
      height: 400rpx;
    }
  }

  .form-item {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;

    .label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 20rpx;
      font-weight: 500;
    }

    .input {
      width: 100%;
      height: 80rpx;
      font-size: 28rpx;
      color: #333;
      border-bottom: 1px solid #f5f5f5;
    }

    .textarea {
      width: 100%;
      height: 160rpx;
      font-size: 28rpx;
      color: #333;
      line-height: 1.5;
      margin-bottom: 20rpx;
      border: 1px solid #eee;
      padding: 10rpx;
      border-radius: 8rpx;
    }

    // 位置信息样式
    .location-info {
      display: flex;
      flex-direction: column;
      gap: 20rpx;

      .location-item {
        display: flex;
        align-items: center;

        .location-label {
          width: 100rpx;
          font-size: 26rpx;
          color: #666;
        }

        .location-input {
          flex: 1;
          height: 60rpx;
          font-size: 26rpx;
          color: #333;
          border: 1px solid #eee;
          border-radius: 6rpx;
          padding: 0 10rpx;
        }
      }
    }
  }

  .btn-wrapper {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    padding: 0 30rpx;
    margin-top: 40rpx;

    .save-btn {
      width: 100%;
    }

    .cancel-btn {
      width: 100%;
      background-color: #f5f5f5;
      color: #666;
    }
  }
}
</style>
